const _ = require('lodash')
const fs = require('fs')
const jsonfile = require('jsonfile')
const { join, dirname } = require('path')

const getFileContent = (path) => fs.readFileSync(path, { encoding: 'UTF-8' })
const getFileJson = (path) => jsonfile.readFileSync(path)

const pathIsExist = (path) => path && fs.existsSync(path)

const mkdirs = (dir) => {
	if (pathIsExist(dir)) {
		return true
	} else {
		if (mkdirs(dirname(dir))) {
			fs.mkdirSync(dir)
			return true
		}
	}
}

const createDir = (filePath) => {
	if (pathIsExist(filePath)) return true
	else {
		return mkdirs(filePath)
	}
}

const createFile = ({ output, outputFileName, render, type, env }) => {
	if (createDir(output)) {
		if (type === 3) {
			jsonfile.writeFileSync(join(output, `./${outputFileName}`), render, { spaces: '\t', EOL: '\r\n' })
		} else {
			fs.writeFileSync(join(output, `./${outputFileName}`), `${render}`, _.noop)
		}

		const typeStr = type === 1 ? 'created' : 'modify'
		const envStr = env === 'vue' ? 'vue' : 'aspnet-core'
		console.log('☕', envStr, outputFileName.green, 'file', typeStr.yellow, 'in', output.underline)
	}
}

module.exports = {
	createFile,
	pathIsExist,
	getFileContent,
	getFileJson,
}
